<template>
  <div class="engineering-manage">
    <!--   start 收款总览 -->
    <ReceivePayment :statistics-obj="statisticsObj" />
    <!--   end 收款总览 -->

    <div class="table-container">
      <!--    start 分组  -->
      <div class="table-container__tabs">
        <DraggableHeaderTab v-model="tableBody" :tab-list="groupList" @get-list="getEngineeringPageList" />
      </div>
      <!--    end 分组  -->

      <div class="table-container__table" v-loading="isLoadingTable">
        <template v-if="tableHeaderData.length">
          <!--      start 操作  -->
          <div class="table-option">
            <div class="radio-item" @click="handelRadio">
              <div class="radio_icon">
                <svg-icon v-if="selectedRowKeys" icon-class="radio_icon_active" size="16"></svg-icon>
                <div v-else class="not_selected"></div>
              </div>
              <div class="radio_label">仅查看待分配任务的工程</div>
            </div>
            <div class="table-option__buttons">
              <el-button type="primary" plain @click="handelExport">
                <template #icon>
                  <svg-icon className="export-icon" icon-class="export_icon" size="16" />
                  <svg-icon className="export-icon--active" icon-class="export_icon_active" size="16" />
                </template>
                导出
              </el-button>
              <el-button type="primary" plain @click="handelResetFilter">重置筛选</el-button>
              <el-button type="primary" plain @click="handelOpenGroupManage">分组及列表配置</el-button>
            </div>
          </div>
          <!--       end 操作  -->
          <el-table
            ref="clientManagerRef"
            :data="tableData"
            stripe
            border
            :header-cell-style="tableHeadStyle"
            :row-class-name="tableRowClassName"
            @sort-change="handleSortChange"
          >
            <!-- todo:可以使用依赖注入方式 -->
            <custom-table-column
              :table-headers="tableHeaderData"
              @handel-filter-data="handelFilterData"
              @set-person="getEngineeringPageList"
              @handel-followup="handelFollowup"
            />
            <el-table-column label="操作" fixed="right" width="100">
              <template #default="{ row }">
                <div class="table-buttons">
                  <el-button type="primary" link @click="handelDetail(row, 'constructionPlan')">详情</el-button>
                  <el-dropdown>
                    <span class="el-dropdown-link">展开</span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item v-for="item in buttons(row).value" @click="() => item.fn(row)">
                          <el-button link type="primary">{{ item.label }}</el-button>
                        </el-dropdown-item>
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <!--      start 分页  -->
          <custom-pagination
            :total="listTotal"
            :background="false"
            v-model:limit="tableParams.size"
            v-model:page="tableParams.current"
            layout="total, sizes ,prev, pager, next, jumper"
            @pagination="handelPage"
          />
          <!--      end 分页  -->
        </template>
        <el-empty v-else />
      </div>
    </div>

    <!--  start 分组及列表配置  -->
    <group-manage v-if="isShowGroupManage" v-model="isShowGroupManage" @check-set-group="checkSetGroup"></group-manage>
    <!--   end  分组及列表配置-->

    <!--  跟进 start  -->
    <followup-drawer v-if="isFollowupDrawer" :customer-id="customerId" v-model="isFollowupDrawer" />
    <!--  跟进 end  -->

    <!--    start 开工确认-->
    <work-confirm
      v-if="showWorkConfirm"
      v-model="showWorkConfirm"
      @workConfirmSave="getEngineeringPageList"
      :currentCustomerId="currentCustomerId"
    ></work-confirm>
    <!--        end 开工确认-->

    <!--    start 停工-->
    <stop-work
      v-model="showStopWork"
      v-if="showStopWork"
      @stopWorkSave="getEngineeringPageList"
      :currentCustomerId="currentCustomerId"
    ></stop-work>
    <!--    end 停工-->

    <!-- 发起整改增减项   -->
    <div class="correction-dialog">
      <el-dialog :show-close="false" v-model="visible" :title="`创建${nameTitle}售后单`" width="450px" center>
        <el-form ref="correctionFormRef" :model="ruleForm" :rules="rules">
          <el-form-item :label="`请选择${nameTitle}关联的合同`" prop="contractId">
            <el-select v-model="ruleForm.contractId" class="m-2" placeholder="请选择" clearable @change="changeContractId">
              <el-option v-for="item in associatedContract" :key="item.contractId" :label="item.title" :value="item.contractId" />
            </el-select>
          </el-form-item>
          <el-form-item label="是否创建报价变更单" prop="radio">
            <el-radio-group v-model="ruleForm.radio" class="ml-4">
              <el-radio :label="1" size="large">是</el-radio>
              <el-radio :label="2" size="large" :disabled="showNo">否</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="visible = false">取消</el-button>
            <el-button type="primary" @click="handleGotoAdd">下一步</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
export default {
  name: "engineeringManage"
};
</script>
<script setup>
import { ref, getCurrentInstance, onMounted } from "vue";
import { useRoute } from "vue-router";
import { useRouteQuery } from "@vueuse/router";
import { cloneDeep } from "lodash";
import CustomTableColumn from "./components/CustomTableColumn";
import ReceivePayment from "./components/ReceivePayment";
import DraggableHeaderTab from "./components/DraggableHeaderTab";
import GroupManage from "./components/GroupManange";
import WorkConfirm from "./components/WorkConfirm";
import StopWork from "./components/StopWork";
import FollowupDrawer from "./components/FollowupDrawer";
import { tableRowClassName, camelToSnake } from "@/utils";
import { aDownFile } from "@/utils/downFile";
import { tableHeadStyle } from "@/config/config";
import { tableHeaders } from "./config/baseConfig";
import * as requestApi from "@/apis/engineeringManage";
import { contractList } from "@/apis/contract";
import { checkReform } from "@/apis/template";
import useComputedParams from "@/hooks/useComputedParams";
import { operateWork } from "@/apis/engineeringManage";

const { proxy } = getCurrentInstance();
const route = useRoute();
const baseRouter = window.microApp.router.getBaseAppRouter();

/**
 * 收款统计
 */
const statisticsObj = ref({});
const getReceiveStatistics = async () => {
  try {
    const { data } = await requestApi.receiveStatistics();
    statisticsObj.value = data ?? {};
  } catch (err) {
    console.log(err);
  }
};

/**
 * 分组Tab
 */
const groupList = ref([]);
const getGroupList = async () => {
  try {
    isLoadingTable.value = true;
    const { data } = await requestApi.groupList();
    groupList.value = data ?? [];
    tableBody.value.groupId = groupList.value[0]?.groupId;
    tableBody.value.groupSys = groupList.value[0]?.groupSys;
    isLoadingTable.value = false;
    getEngineeringPageList();
  } catch (err) {
    isLoadingTable.value = false;
    console.log(">>>>getGroupList", err);
  }
};

/**
 * 表格数据
 */
const isLoadingTable = ref(false);
const unAssigned = useRouteQuery("unAssigned");
const tableData = ref([]);
const tableHeaderData = ref([]);
const listTotal = ref(0);
const tableParams = ref({
  current: 1,
  size: 10
});
const tableBody = ref({
  groupId: "",
  groupSys: true,
  select: [
    // {
    //   filterId: "",
    //   compare: "",
    //   value:[]
    // }
  ],
  sort: [
    // {
    //   id:"",
    //   isAsc: false
    // }
  ],
  disTask: unAssigned.value
});
const showSetCustomerComp = ref(false); //是否显示设为重点客户组件
const getEngineeringPageList = async () => {
  showSetCustomerComp.value = false;
  try {
    isLoadingTable.value = true;
    const { data } = await requestApi.engineeringPageList(tableParams.value, tableBody.value);
    const { tableFields, tablePages } = data;
    // const showDataIds =
    //   tableFields?.map(item => {
    //     return item.value;
    //   }) || [];
    // tableHeaderData.value = tableHeaders.filter(item => {
    //   return showDataIds.includes(item.value);
    // });

    tableHeaderData.value = tableFields.map(item => {
      const obj = tableHeaders.find(subItem => subItem.value === item.value);
      return {
        ...item,
        ...obj
      };
    });
    listTotal.value = tablePages?.total ?? 0;
    tableData.value = tablePages?.list ?? [];
    isLoadingTable.value = false;
    showSetCustomerComp.value = true;
  } catch (err) {
    isLoadingTable.value = false;
    showSetCustomerComp.value = true;
    console.log("getEngineeringPageList>>>", err);
  }
};
const handelPage = val => {
  tableParams.value.current = val.page;
  tableParams.value.size = val.limit;
  getEngineeringPageList();
};

/**
 * 排序
 */
const handleSortChange = ({ prop, order }) => {
  tableBody.value.sort = order
    ? [
        {
          id: camelToSnake(prop),
          isAsc: order === "ascending"
        }
      ]
    : [];
  getEngineeringPageList();
};

/**
 * 仅查看待分配任务的工程
 */
const selectedRowKeys = ref(false);
const handelRadio = () => {
  selectedRowKeys.value = !selectedRowKeys.value;
  tableBody.value.disTask = selectedRowKeys.value;
  getEngineeringPageList();
};

/**
 * 导出
 */
const handelExport = async () => {
  try {
    isLoadingTable.value = true;
    const { data } = await requestApi.exportExcel(tableBody.value);
    isLoadingTable.value = false;
    if (!data) return;
    aDownFile(data, "工程管理");
  } catch (err) {
    isLoadingTable.value = false;
    console.log(err);
  }
};

/**
 * 分组及列表配置
 */
const isShowGroupManage = ref(false);
const handelOpenGroupManage = () => {
  isShowGroupManage.value = true;
};
// 校验是否刷新页面
const checkSetGroup = isRefresh => {
  if (!isRefresh) return;
  tableParams.value.current = 1;
  getGroupList();
};

/**
 * 筛选
 * todo: 是否选择筛选条件可以放在子组件中
 */
const handelFilterData = data => {
  const { filterData, columnIndex } = data;
  const _hasData = () => {
    return filterData?.some(item => {
      return item.value?.length && (item.value[0] || item.value[0] === 0);
    });
  };
  tableHeaderData.value[columnIndex].filterList = cloneDeep(filterData);
  tableHeaderData.value[columnIndex].isSetFilter = _hasData();
  tableBody.value.select = [];
  (tableHeaderData.value ??= [])
    .filter(item => {
      return item.isSetFilter;
    })
    .reduce(
      (pre, cur) => {
        pre.push(...cur.filterList);
        return pre;
      },
      (tableBody.value.select ??= [])
    );
  tableParams.value.current = 1;
  getEngineeringPageList();
};

/**
 * 重置筛选
 */
const handelResetFilter = () => {
  tableParams.value.current = 1;
  tableBody.value.select = [];
  tableHeaderData.value.forEach(item => {
    item.isSetFilter = false;
  });
  getEngineeringPageList();
};

/**
 * 跟进
 */
const isFollowupDrawer = ref(false);
const customerId = ref("");
const handelFollowup = data => {
  customerId.value = data.customerId;
  isFollowupDrawer.value = true;
};

/**
 * 详情
 */
const handelDetail = (data, funcTab) => {
  baseRouter.push({
    path: "/crm/client-info",
    query: {
      funcTab,
      customerId: data.customerId,
      afterSalesType: data.afterSalesType,
      backPageUrl: "/projectmanage/engineering-manage"
    }
  });
};

/**
 * 分配
 * @param row
 */
const handelDistribution = row => {
  baseRouter.push({
    path: "/crm/distribution",
    query: {
      customerId: row.customerId,
      reformType: false,
      stageType: 2,
      backPageUrl: "/projectmanage/engineering-manage"
    }
  });
};
const currentCustomerId = ref("");
/**
 * 开工确认
 */
const showWorkConfirm = ref(false);
const handelWorkStartConfirm = row => {
  currentCustomerId.value = row.customerId;
  showWorkConfirm.value = true;
};
/**
 * 重置任务
 * @param data
 */
const handelResetTask = data => {
  proxy.$modal
    .confirm("除该客户已完成的任务外，其他任务将按最新流程模板重发，是否确认？", "确认操作？")
    .then(async () => {
      try {
        isLoadingTable.value = true;
        await requestApi.resetClientInfo(data.customerId);
        isLoadingTable.value = false;
        proxy.$modal.msgSuccess("重置成功");
      } catch (err) {
        isLoadingTable.value = false;
      }
    })
    .catch(() => {});
};
/**
 * 复工
 */
const handelReturnWork = data => {
  proxy.$modal
    .confirm("请确认是否开工?")
    .then(async () => {
      isLoadingTable.value = true;
      let params = { customerId: data.customerId, type: 2 };
      await requestApi.operateWork(params);
      proxy.$modal.msgSuccess("工地开工成功");
      await getEngineeringPageList();
    })
    .catch(() => {});
};
/**
 * 停工
 */
const showStopWork = ref(false);
const handelStopWork = data => {
  currentCustomerId.value = data.customerId;
  showStopWork.value = true;
};
/**
 * 取消停工申请
 */
const handelCancelStopWork = async data => {
  try {
    await operateWork({ customerId: data.customerId, type: 3 });
    proxy.$modal.msgSuccess("取消停工成功");
  } catch (err) {
    console.log(err, "<<operateWork");
  }
};

/**
 * 整改/增减项
 */
const nameTitle = ref("");
const associatedContract = ref([]);
const visible = ref(false);
const showNo = ref(false);
/**
 *  获取关联合同
 * @param rowData
 */
const getContractList = async rowData => {
  const { data } = await contractList({ customerId: rowData.customerId });
  associatedContract.value = data || [];
  if (data.length > 0) {
    visible.value = true;
    if (nameTitle.value === "增减项") {
      ruleForm.value.radio = 1;
      showNo.value = true;
    } else {
      showNo.value = false;
    }
    if (data.length === 1) {
      ruleForm.value = { ...ruleForm.value, ...data[0] };
    } else {
      ruleForm.value.contractId = "";
    }
  } else {
    if (nameTitle.value === "增减项") {
      proxy.$modal.msgError("该客户无合同，不可发起整改");
    } else {
      baseRouter.push({
        path: "/crm/after-sales-order",
        query: {
          budgetId: ruleForm.value.budgetId,
          customerId: customerId.value,
          afterSalesType: 1
        }
      });
    }
  }
};
/**
 * 选择关联合同
 * @param contractId
 */
const changeContractId = contractId => {
  const customerObj = associatedContract.value.find(item => item.contractId === contractId);
  if (customerObj.contractId) {
    ruleForm.value = {
      ...ruleForm.value,
      ...customerObj
    };
  }
};
/**
 * 发起整改
 */
const ruleForm = ref({
  radio: 2,
  contractId: ""
});
const rules = {
  radio: {
    required: true,
    message: "请选择",
    trigger: "change"
  },
  contractId: {
    required: true,
    message: "请选择关联的合同",
    trigger: "change"
  }
};
const handelInitiateRectification = data => {
  nameTitle.value = "整改";
  customerId.value = data.customerId;
  ruleForm.value = {
    radio: 2,
    contractId: ""
  };
  getContractList(data);
};
/**
 * 发起增减项
 */
const handelInitiateChange = data => {
  nameTitle.value = "增减项";
  customerId.value = data.customerId;
  ruleForm.value = {
    radio: 2,
    contractId: ""
  };
  getContractList(data);
};
/**
 * 创建增减项整改
 */
const handleGotoAdd = async () => {
  proxy.$refs.correctionFormRef.validate(async valid => {
    if (!valid) return;
    //是否创建预算报价增减项单 1是 2否
    if (ruleForm.value.radio === 1) {
      const { data } = await checkReform(ruleForm.value.contractId);
      if (data !== true) {
        return proxy.$modal.msgError("存在进行中的变更单，无法再次发起！");
      }
      const afterSalesType = nameTitle.value === "整改" ? 1 : 3;
      const routeUrl = baseRouter.resolve({
        path: "/designer/quote-price/following/change",
        query: {
          budgetId: ruleForm.value.budgetId,
          contractId: ruleForm.value.contractId,
          customerId: customerId.value,
          afterSalesType
        }
      });
      window.open(routeUrl.href, "_blank");
      visible.value = false;
    } else {
      baseRouter.push({
        path: "/crm/after-sales-order",
        query: {
          budgetId: ruleForm.value.budgetId,
          contractId: ruleForm.value.contractId,
          customerId: customerId.value,
          afterSalesType: nameTitle.value === "整改" ? 1 : 3
        }
      });
      visible.value = false;
    }
  });
};

/**
 * 操作按钮
 */
const commonOperates = {
  assign: {
    label: "分配",
    fn: data => handelDistribution(data)
  },
  confirmStart: {
    label: "开工确认",
    fn: data => handelWorkStartConfirm(data)
  },
  resetTask: {
    label: "重置任务",
    fn: data => handelResetTask(data)
  },
  initiateChange: {
    label: "发起增减项",
    fn: data => handelInitiateChange(data)
  },
  adjustPlan: {
    label: "调整计划",
    fn: data => handelDetail(data, "constructionPlan")
  },
  initiateRectification: {
    label: "发起整改",
    fn: data => handelInitiateRectification(data)
  },
  applyShutdown: {
    label: "停工申请",
    fn: data => handelStopWork(data)
  },
  resumeWork: {
    label: "复工",
    fn: data => handelReturnWork(data)
  },
  cancelShutdown: {
    label: "取消停工申请",
    fn: data => handelCancelStopWork(data)
  }
  // applyFinalSettlement: {
  //   label: "申请决算",
  //   fn: data => {
  //     console.log("申请决算", data);
  //   }
  // }
};
const constructionStatus = new Map([
  [
    "not_start",
    {
      label: "未开始",
      operates: [commonOperates.assign, commonOperates.confirmStart, commonOperates.resetTask, commonOperates.initiateChange]
    }
  ],
  [
    "ing",
    {
      label: "进行中",
      operates: [
        commonOperates.assign,
        commonOperates.adjustPlan,
        commonOperates.resetTask,
        commonOperates.initiateRectification,
        commonOperates.initiateChange,
        commonOperates.applyShutdown
      ]
    }
  ],
  [
    "shutdown",
    {
      label: "已停工",
      operates: [commonOperates.assign, commonOperates.resumeWork]
    }
  ],
  [
    "shutdown_ing",
    {
      label: "停工审核中",
      operates: [
        commonOperates.assign,
        commonOperates.adjustPlan,
        commonOperates.resetTask,
        commonOperates.initiateRectification,
        commonOperates.initiateChange,
        commonOperates.cancelShutdown
      ]
    }
  ],
  [
    "complete",
    // commonOperates.applyFinalSettlement,
    {
      label: "已交付",
      operates: [commonOperates.initiateRectification, commonOperates.initiateChange]
    }
  ],
  [
    "time_out",
    {
      label: "已超期",
      operates: []
    }
  ],
  [
    "delay_risk",
    {
      label: "延期风险",
      operates: []
    }
  ]
]);
const buttons = useComputedParams(rowData => {
  const data = rowData.exp ? rowData.expStatus : rowData.buildStatus;
  if (["time_out", "delay_risk"].includes(data)) {
    return constructionStatus.get(rowData.buildStatus)?.operates;
  }
  return constructionStatus.has(data) ? constructionStatus.get(data)?.operates : [];
});

onMounted(() => {
  const unAssigned = route.query.unAssigned ?? "";
  if (unAssigned == 1) {
    selectedRowKeys.value = true;
    tableBody.value.disTask = true;
  }
  getGroupList();
  getReceiveStatistics();
});
</script>

<style scoped lang="scss">
@import "engineering";
</style>
<style lang="scss">
.engineering-manage {
  td {
    .cell {
      display: block !important;
    }
  }
}
</style>
